package org.origin.ferret.system.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.origin.centre.model.result.R;
import org.origin.centre.support.captcha.Captcha;
import org.origin.centre.support.utils.BasicUtil;
import org.origin.centre.utils.RedisUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 验证码-接口
 *
 * @author ferret
 * @version 2024-05-08
 */
@Slf4j
@RestController
@Tag(name = "验证码-接口")
@RequiredArgsConstructor
@RequestMapping("${origin.api:}/without/sys/code")
public class SysCodeController {
    private final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";
    private final Captcha captcha = new Captcha();

    @Operation(summary = "1.生成图形验证码", description = "生成图形验证码")
    @GetMapping(value = "/captcha/{key}")
    public R<String> captcha(@PathVariable("key") String key) {
        //生成验证码
        String code = RandomUtil.randomString(BASE_CHECK_CODES, 4);
        String lowerCaseCode = code.toLowerCase();
        // 加入密钥作为混淆，避免简单的拼接，被外部利用
        String origin = lowerCaseCode + key + "signatureSecret";
        String realKey = BasicUtil.encodeMD5(origin);
        RedisUtil.set(realKey, lowerCaseCode, 60, TimeUnit.SECONDS);
        log.info("验证码 key: {}, value: {}", realKey, lowerCaseCode);
        //返回前端
        String base64 = captcha.generate(code);
        return R.ok("获取验证码成功", base64);
    }

}
